package com.cndw.kungfu.model.activity.holiday;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.cndw.kungfu.config.ConstantsConfig;
import com.cndw.kungfu.config.ConstantsLog;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.HolidayCommSerialize;
import com.cndw.kungfu.model.goods.domain.SysModeAwards;
import com.cndw.kungfu.model.pvp.api.FlowerApiClient;
import com.cndw.kungfu.model.sys.LogServer;
/**
 * 主播活动数据
 * 
 * @author Everest
 *
 */
public class MMFlowerData implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1702691331125766674L;
	private static int endTime;
	/**
	 * 献花集合
	 */
	private Map<Long, Integer> dayMap = new ConcurrentHashMap<Long, Integer>();
	private Map<Long, Integer> weekMap = new ConcurrentHashMap<Long, Integer>();
	
	/**
	 * 单服排行
	 */
	private List<MMFlowerPlayer> sRanking = new ArrayList<MMFlowerPlayer>();
	
	private static int lastRankTime = 0;
	
	private int lastAward = 0;
	
	private boolean over = false;
	
	/**
	 * 主播活动献花记录
	 */
	private ConcurrentLinkedQueue<MMFlowerLog> mmfLog = new ConcurrentLinkedQueue<MMFlowerLog>();
	
	/**
	 * 全服前30
	 */
	private ArrayList<MMFlowerPlayer> tops = new ArrayList<MMFlowerPlayer>();
	
	/**
	 * 主播得到鲜花数
	 */
	private Map<Integer, Integer> mmFlower = new ConcurrentHashMap<Integer, Integer>();
	
	static {
		endTime = TimeProcesser.getUnixTimeSilent("2012-10-22 21:40:00");
	}
	
	public int getEndTime() {
		return endTime;
	}
	
	public static MMFlowerData getInstance() {
		return HolidayCommSerialize.getInstance().getMMFlowerData();
	}
	
	public void addMMFLowerLog(MMFlowerLog mmFlower) {
		mmfLog.add(mmFlower);
		if (mmfLog.size() > 30) {
			mmfLog.poll();
		}
	}
	
	public ConcurrentLinkedQueue<MMFlowerLog> getMMFlowerLog() {
		return mmfLog;
	}
	
	public void flower(long pid, int num) {
		if (dayMap.containsKey(pid)) {
			dayMap.put(pid, dayMap.get(pid) + num);
		} else {
			dayMap.put(pid, num);
		}
		weekMapAdd(pid, num);
	}
	
	public void weekMapAdd(long pid, int num) {
		if (weekMap.containsKey(pid)) {
			weekMap.put(pid, weekMap.get(pid) + num);
		} else {
			weekMap.put(pid, num);
		}
	}
	
	public int weekMapGet(long playerId) {
		if (weekMap.containsKey(playerId)) {
			return weekMap.get(playerId);
		} else {
			return 0;
		}
	}
	
	public void mmFlowerAdd(int num, int mmId) {
		if (mmFlower.containsKey(mmId)) {
			mmFlower.put(mmId, mmFlower.get(mmId) + num);
		} else {
			mmFlower.put(mmId, num);
		}
	}
	
	public Map<Integer, Integer> getMMFlower() {
		return mmFlower;
	}
	
	public int getFlowerNum(long playerId) {
		if (dayMap.containsKey(playerId)) {
			return dayMap.get(playerId);
		}
		return 0;
	}
	
	public List<Entry<Long, Integer>> getSingleRankList(Map<Long, Integer> data) {
		List<Entry<Long, Integer>> list = new ArrayList<Map.Entry<Long,Integer>>(data.entrySet());
		Collections.sort(list, new Comparator<Entry<Long, Integer>>() {
			@Override
			public int compare(Entry<Long, Integer> o1, Entry<Long, Integer> o2) {
				return o2.getValue() - o1.getValue();
			}
		});
		return list;
	}
	
	public void singleRank () {
		if (sRanking == null) {
			sRanking = new ArrayList<MMFlowerPlayer>();
		} else {
			sRanking.clear();
		}
		
//		if (flowerMap == null) {
//			flowerMap = new ConcurrentHashMap<Long, Object[]>();
//			return;
//		}
		
		if (dayMap.size() <= 0) {
			return;
		}
		List<Entry<Long, Integer>> list = getSingleRankList(dayMap);
		int orderId = 0;
		for (Entry<Long, Integer> e : list) {
			Player player = Context.getPlayerServer().getByPlayerId(e.getKey());
			if (player == null) {
				continue;
			}
			orderId ++;
			MMFlowerPlayer mfp = new MMFlowerPlayer();
			mfp.setCount(e.getValue());
			mfp.setPid(e.getKey());
			mfp.setPn(player.getPlayerName());
			sRanking.add(mfp);
			if (orderId >= 10) {
				break;
			}
		}
		lastRankTime = TimeProcesser.getUnixTime();
		
	}
	
	public List<MMFlowerPlayer> getSilgleRanking() {
		if (TimeProcesser.getUnixTime() - lastRankTime >= 180) {
			synchronized (this) {
				if (TimeProcesser.getUnixTime() - lastRankTime >= 180) {
					singleRank();
				}
			}
		}
		return sRanking;
	}
	
	public void runAward() {
		if (getEndTime() <= lastAward) {
			return;
		}
		//每天21：35结算日榜奖励
		int initialDelay = 77700 - (TimeProcesser.getUnixTime() - TimeProcesser.getMorningTime());
		if (initialDelay < 0) {
			initialDelay += 86400;
		}
		Context.getTimerServer().scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				try {
					if (lastAward >= getEndTime() - 300) {
						return;
					}
					singleRank();
					int orderId = 0;
					for (MMFlowerPlayer e : sRanking) {
						orderId ++;
						int aTypeId = orderId == 1 ? 1 : orderId == 2 ? 2 : orderId == 3 ? 3 : 4;
						SysModeAwards sysAwards = SysModeAwards.get(103, aTypeId);
						if (sysAwards == null) {
							continue;
						}
						Player player = Context.getPlayerServer().getByPlayerId(e.getPid());
						if (player == null) {
							continue;
						}
						String title = LanguageLib.get("holiday.mmflower.title");
						String content = LanguageLib.get("holiday.mmflower.comtent", orderId);
						Context.getMessageServer().sendSysMail(e.getPid(), e.getPn(), title, content, sysAwards.makeAttachment());
						LogServer.recordLog(player, ConstantsLog.activity, 90473, orderId, sysAwards.getTitle());
					}
					dayMap.clear();
					lastAward = TimeProcesser.getUnixTime();
					commitSync();
					LogUtil.getMain().debug("mm flower everyday award ...");
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
		}, initialDelay, 86400);
		LogUtil.getMain().info("mm flower everyday "+initialDelay);
	}
	
	public Collection<MMFlowerPlayer> getTopList() {
		Collection<MMFlowerPlayer> list = new ArrayList<MMFlowerPlayer>();
		
		List<Entry<Long, Integer>> orderList = getSingleRankList(weekMap);
		
		for (Entry<Long, Integer> e : orderList) {
			MMFlowerPlayer mfp = new MMFlowerPlayer();
			mfp.setCount(e.getValue());
			mfp.setPid(e.getKey());
			Player player = Context.getPlayerServer().getByPlayerId(e.getKey());
			mfp.setPn(player.getPlayerName());
			mfp.setSid(ConstantsConfig.getSysCgServiceId());
			list.add(mfp);
			if (list.size() >= 30) {
				break;
			}
		}
		
		return list;
	}
	
	public boolean isForbidTime() {
		int s = TimeProcesser.getUnixTime() - TimeProcesser.getMorningTime();
		if (TimeProcesser.getUnixTime() >= endTime || (s >= 77400 && s <= 79200)) {//每天21：30-22：00禁止献花
			return true;
		}
		return false;
	}
	
	public void addLog(final MMFlowerLog log) {
		Context.getTimerServer().execute(new Runnable() {
			@Override
			public void run() {
				FlowerApiClient.addFlowerLog(log);
			}
		});
	}
	
	public ArrayList<MMFlowerPlayer> getTops() {
		return tops;
	}
	
	public void setTops(ArrayList<MMFlowerPlayer> topsTmp) {
		tops = topsTmp;
		commitSync();
	}
	
	public void over() {
		over = true;
		commitSync();
	}
	
	public boolean isOver() {
		return over;
	}
	
	public void commitSync() {
		HolidayCommSerialize.getInstance().commitSync();
	}

}
